package com.linkcard.list.action;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.linkcard.commen.tools.Helper;
import com.linkcard.commen.tools.Page;
import com.linkcard.list.manager.BusinessManager;
import com.linkcard.list.manager.CategoryManager;
import com.linkcard.list.model.Business;
import com.linkcard.list.model.Category;
import com.linkcard.user.model.WebsiteColumns;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class BusinessAction extends ActionSupport {

	private  BusinessManager businessManager=null;
	private CategoryManager categoryManager=null;
	private Business business=null;
	private int columnId;
	private Page pageObj=null;
	private int page;
	private int rows;
	private String searchStr=null;
	private String ids=null;
	private List list=null;
	private List categoryList=null;
	private String path=null;
	private List branchBusinessList=null;
	public int getColumnId() {
		return columnId;
	}
	public void setColumnId(int columnId) {
		this.columnId = columnId;
	}
	public Business getBusiness() {
		return business;
	}
	public void setBusiness(Business business) {
		this.business = business;
	}
	@SuppressWarnings("unchecked")
	@Override
	public String execute() throws Exception {
		pageObj=new Page();
		pageObj.setCurrentPage(page);
		pageObj.setPageSize(10);
		list=new ArrayList();
		WebsiteColumns column=null;
		List columnList=(List)ActionContext.getContext().getApplication().get("columns");
		for(int i=0;i<columnList.size();i++)
		{
			 column=(WebsiteColumns)columnList.get(i);
			if(column.getId()==2)
			{
				path="<a href='"+column.getUrl()+".action?columnId="+column.getId()+"'>"+column.getName()+"</a>";
				break;
			}
		}
		List searchList=this.businessManager.businessList(pageObj,(searchStr==null)?"":Helper.decode(searchStr));
		for(int i=0;i<searchList.size();i++)
		{
			Object[] objs=(Object[])searchList.get(i);
			List temp=new ArrayList();
			temp.add(objs[0]);
			temp.add(objs[1]);
			Business business=(Business)objs[0];
			if(business.getSubCategoryId()!=-2)
			{
				Category subCategory=categoryManager.findCategory(business.getSubCategoryId());
			    temp.add(subCategory);
			}else
			{
				Category subCategory=new Category();
				subCategory.setName("");
			    temp.add(subCategory);
			}
			list.add(temp);
		}
		categoryList=this.categoryManager.categoryListBySelect(2,0);
		if(searchStr==null||searchStr.split("_")[0].equals("-2"))
		{
		     path+=">>所有信息";
		     path="<span>位置："+path+"</span><h1>加盟商家</h1>";
		}else
		{
			String[] cids=searchStr.split("_");
			path+=">><a href='business.action?page=1&searchStr="+cids[0]+"_-2_'>"+categoryManager.findCategory(Integer.parseInt(cids[0])).getName()+"</a>";
		    if(!cids[1].equals("-2"))
		    {
		    	path+=">><a href='business.action?page=1&searchStr="+searchStr+"'>"+categoryManager.findCategory(Integer.parseInt(cids[1])).getName()+"</a>";
		    }
		    path="<span>位置："+path+"</span><h1>"+categoryManager.findCategory(Integer.parseInt(cids[0])).getName()+"</h1>";
		}
		return "success";
	}
	//添加商家
	public String addBusiness()throws Exception{
		this.clearMessages();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		business.setDatetime(sdf.format(new Date()));
		business.setRecommend((business.getRecommend()==null)?0:business.getRecommend());
		boolean isSuccess=this.businessManager.addBusiness(business);
		if(!isSuccess)
		{
			this.addActionMessage("添加失败");
			return "Business";
		}
		business=null;
		return "List";
	}
	//获得商家列表
	public String businessListForJson() throws Exception{
		pageObj=new Page();
		pageObj.setCurrentPage(page);
		pageObj.setPageSize(rows);
		searchStr=Helper.decode(searchStr);
		List list=this.businessManager.businessList(pageObj,searchStr);
		JSONObject json=new JSONObject();
		JSONArray jsonArray=new JSONArray();
		for(int i=0;i<list.size();i++)
		{
			Object[] obj=(Object[])list.get(i);
			Business business=(Business)obj[0];
			Category category=(Category)obj[1];
			JSONObject temp=new JSONObject();
			temp.put("id", business.getId());
			temp.put("address", business.getAddress());
			temp.put("category", category.getName());
			Category subCategory=categoryManager.findCategory(business.getSubCategoryId());
			temp.put("subCategory",(subCategory!=null)?subCategory.getName():"");
			temp.put("datetime", business.getDatetime());
			temp.put("vipDiscount", business.getVipDiscount());
			temp.put("goldDiscount", business.getGoldDiscount());
			temp.put("image", business.getImage());
			temp.put("introduction",business.getIntroduction());
			temp.put("recommend",(business.getRecommend()==0)?"否":"是");
			temp.put("name", business.getName());
			temp.put("tel", business.getTel());
			temp.put("website", business.getWebsite());
			temp.put("opt","<a href='business!businessDetial.action?business.id="+business.getId()+"'target='_blank'>查看</a>&nbsp;&nbsp;<a href='business!modify.action?columnId="+columnId+"&business.id="+business.getId()+"'>修改</a>&nbsp;&nbsp;<a href='javascript:void(0);' onclick='deleteBusiness("+business.getId()+");'>删除</a>");
			jsonArray.add(temp);
		}
		json.put("total", pageObj.getRowCount());
		json.put("rows", jsonArray);
		backText(json.toString());
		return "Data";
	}
	//获得商家列表
	@SuppressWarnings("unchecked")
	public String businessOptionForJson() throws Exception{
		List list=this.businessManager.businessList(null,"");
		JSONArray jsonArray=JSONArray.fromObject(list);
		backText(jsonArray.toString());
		return "Data";
	}
	//修改商家
	public String modify() throws Exception{
		this.clearMessages();
		business=this.businessManager.findBusiness(business.getId());
		return"Business";
	}
	public String modifyBusiness() throws Exception{
		business.setRecommend((business.getRecommend()==null)?0:business.getRecommend());
		boolean isSuccess=this.businessManager.modifyBusiness(business);
		if(!isSuccess)
		{
			this.addActionMessage("修改失败");
			return"Business";
		}
		return"List";
	}
	//删除商家
	public String deleteBusiness() throws Exception{
		boolean isSuccess=this.businessManager.deleteBusiness(ids);
		JSONObject json=new JSONObject();
		json.put("info",isSuccess);
		backText(json.toString());
		return "Data";
	}
	//单个商家
	public String businessDetial() throws Exception{
		categoryList=this.categoryManager.categoryListBySelect(2,0);
		business=this.businessManager.findBusiness(business.getId());
		branchBusinessList=new ArrayList();
		if(business.getPname()!=null&&!business.getPname().equals(""))
		{
			
		  List tempList=this.businessManager.branchBusinessList(business.getPname());
		  for(int i=0;i<tempList.size();i++)
			{
				Object[] objs=(Object[])tempList.get(i);
				List temp=new ArrayList();
				temp.add(objs[0]);
				temp.add(objs[1]);
				Business business=(Business)objs[0];
				if(business.getSubCategoryId()!=-2)
				{
					Category subCategory=categoryManager.findCategory(business.getSubCategoryId());
				    temp.add(subCategory);
				}else
				{
					Category subCategory=new Category();
					subCategory.setName("");
				    temp.add(subCategory);
				}
				branchBusinessList.add(temp);
			}
		}
		WebsiteColumns column=null;
		List columnList=(List)ActionContext.getContext().getApplication().get("columns");
		for(int i=0;i<columnList.size();i++)
		{
			 column=(WebsiteColumns)columnList.get(i);
			if(column.getId()==2)
			{
				path="<a href='"+column.getUrl()+".action?columnId="+column.getId()+"'>"+column.getName()+"</a>";
				break;
			}
		}
		
			Category category=categoryManager.findCategory(business.getCategoryId());
			path+=">><a href='business.action?page=1&searchStr="+category.getId()+"_-2_'>"+category.getName()+"</a>";
		    if(business.getSubCategoryId()!=-2)
		    {
		    	Category subCategory=categoryManager.findCategory(business.getSubCategoryId());
		    	path+=">><a href='business.action?page=1&searchStr="+category.getId()+"_"+subCategory.getId()+"_'>"+subCategory.getName()+"</a>";
		    }
		
		return "BusinessDetial";
	}
	//返回文本
	public void backText(String data) throws Exception
	{
		ServletActionContext.getResponse().setContentType ("text/html;charset=utf-8");
		
		  PrintWriter out = ServletActionContext.getResponse().getWriter();
		  out.print(data);
		  out.flush();
		  out.close();
	}
	public BusinessManager getBusinessManager() {
		return businessManager;
	}
	public void setBusinessManager(BusinessManager businessManager) {
		this.businessManager = businessManager;
	}
	public Page getPageObj() {
		return pageObj;
	}
	public void setPageObj(Page pageObj) {
		this.pageObj = pageObj;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public void setRows(int rows) {
		this.rows = rows;
	}
	public String getSearchStr() {
		return searchStr;
	}
	public void setSearchStr(String searchStr) {
		this.searchStr = searchStr;
	}
	public CategoryManager getCategoryManager() {
		return categoryManager;
	}
	public void setCategoryManager(CategoryManager categoryManager) {
		this.categoryManager = categoryManager;
	}
	public void setIds(String ids) {
		this.ids = ids;
	}
	public List getList() {
		return list;
	}
	public void setList(List list) {
		this.list = list;
	}
	public List getCategoryList() {
		return categoryList;
	}
	public void setCategoryList(List categoryList) {
		this.categoryList = categoryList;
	}
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	public List getBranchBusinessList() {
		return branchBusinessList;
	}
	public void setBranchBusinessList(List branchBusinessList) {
		this.branchBusinessList = branchBusinessList;
	}

}
